package com.sunshine.wrongquestionset.activity.exercise

import android.content.Intent
import android.os.Bundle
import android.os.PersistableBundle
import android.text.Html
import android.view.Menu
import android.view.MenuItem
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.sunshine.wrongquestionset.R
import com.sunshine.wrongquestionset.activity.base.BaseActivity
import com.sunshine.wrongquestionset.room.entity.QuestionEntity
import es.dmoral.toasty.Toasty
import kotlinx.android.synthetic.main.activity_exercise.*

class ExerciseActivity : BaseActivity() {

    private lateinit var viewModel: ExerciseViewModel
    private lateinit var adapter: ExerciseFragmentAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_exercise)
        setTitle(getString(R.string.label_exercise))

        viewModel = ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(application)).get(ExerciseViewModel::class.java)

//        viewModel.getAllQuestion(getLoginUserId()).observe(this, Observer {
//            setQuestionList(it)
//
//            adapter = ExerciseFragmentAdapter(this, it)
//            viewPager.adapter = adapter
//        })

        //使最大练习量为设置值
        val maxCount = viewModel.getMaxExerciseCount()
        if (getQuestionList()?.size?:0 > maxCount) {
            val tempQuestionList = ArrayList<QuestionEntity>()
            getQuestionList()?.forEach {
                if (tempQuestionList.size >= maxCount) return@forEach
                tempQuestionList.add(it)
            }
            setQuestionList(tempQuestionList)
        }
        adapter = ExerciseFragmentAdapter(this, getQuestionList())
        viewPager.adapter = adapter

        //开始计时
        chronometer.start()
    }

    /**
     * 设置当前滚动到的位置，用于点击题目标签跳转到那道题目
     */
    fun setViewPagerCurrentItem(position: Int) {
        viewPager.currentItem = position
    }

    /**
     * 通知做题情况更新
     */
    fun notifyCardFragmentDataSetChanged() {
        adapter.getExerciseCardFragment().notifyDataSetChanged()

    }

    /**
     * 返回键二次确认
     */
    private fun backWarning() {
        val builder = MaterialAlertDialogBuilder(this)
        builder.apply {
            setTitle(getString(R.string.warning_title))
            setMessage(Html.fromHtml(getString(R.string.back_warning)))
            setNegativeButton("返回") {_, _ ->
                finish()
            }
            setPositiveButton("继续答题") {_, _ ->}

        }
        builder.create().show()
    }

    override fun onBackPressed() {
        backWarning()
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_exercise, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            android.R.id.home -> {
                backWarning()
                return true
            }
            R.id.exercise_card -> {
                viewPager.currentItem = questionList?.size?.plus(1)?:1
            }
            R.id.to_save_answer -> {
                val builder = MaterialAlertDialogBuilder(this)
                builder.apply {
                    setTitle(getString(R.string.warning_title))
                    if (exerciseResultMap.size < questionList?.size?:0) {
                        setMessage(Html.fromHtml(getString(R.string.to_save_answer_warning_not_done)))
                    } else {
                        setMessage(getString(R.string.to_save_answer_warning))
                    }

                    setNegativeButton("确定") {_, _ ->
                        ExerciseScoreActivity.setQuestionList(questionList)
                        ExerciseScoreActivity.setAnswerMap(exerciseResultMap)

                        ExerciseScoreActivity.exerciseTime = chronometer.contentDescription.toString()
                        startActivity(Intent(this@ExerciseActivity, ExerciseScoreActivity::class.java))
                        this@ExerciseActivity.finish()
                    }
                    setPositiveButton("检查一下") {_, _ ->}
                }
                builder.create().show()
            }
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onDestroy() {
        super.onDestroy()
        //释放问题列表
        questionList = null
        exerciseResultMap = HashMap()
    }

    companion object {
        var subjectName = ""
        private var questionList: List<QuestionEntity>? = null

        /**
         * 练习结果Map
         * key   题目所在位置
         * value 题目答案信息
         */
        private var exerciseResultMap = HashMap<Int, ExerciseBean>()
        /**
         * 一个静态方法
         * 用于设置要练习的题目，可能不是一个好的方法，但是比intent简单
         */
        fun setQuestionList(list: List<QuestionEntity>?) {
            questionList = list
        }

        fun getQuestionList(): List<QuestionEntity>? {
            return questionList
        }

        fun addAnswer(position: Int, questionId: Int, answerPath: String) {
            exerciseResultMap[position] = ExerciseBean(questionId, answerPath)
        }

        fun removeAnswer(position: Int) {
            exerciseResultMap.remove(position)
        }

        fun getAnswerMap(): HashMap<Int, ExerciseBean> {
            return exerciseResultMap
        }
    }
}